<script lang="ts" setup>

import {useRoute} from 'vue-router'
import {onMounted, ref} from "vue";
import axios from "axios";
import PerfumeItem from "@/components/PerfumeItem.vue";
// 获取当前路由对象
const route = useRoute()

const page = ref(1)
const pageItem = ref(20)
const pageTotal = ref(0)

const perfumeList = ref([])
const expandedSearch = ref(false)
const rankFlag = ref("上线时间")
const rankDic = ref("正序")//1为正序，0位倒序，如果连续两次选择一样，那么就为相反
const rankDicOptions = [
  '正序',
  "倒序"
]
const rankOptions = ["上线时间", "销量", "价格"]
const searchText = ref('')

//搜索
const searchPerfume = () => {
  perfumeList.value = []//初始化
  page.value = 1
  pageItem.value = 20
  pageTotal.value = 0
  getPerfumeData(page.value, pageItem.value)

}
const brandId = ref(0)//品牌id
const brandOptions = ref([])//品牌列表
const brandText = ref('')//品牌名称
const brandOptionsText = ref([])//品牌名称列表
const sexOptions = ['对他来说', '对她来说', '中性']

const sex = ref('')

const priceStart = ref(0)
const priceEnd = ref(0)
const reset = () => {
  rankFlag.value = "上线时间"
  sex.value = ""
  brandId.value = 0
  priceStart.value = 0
  priceEnd.value = 0
  searchText.value = ""
  priceBetween.value = {
    min:3000,
    max:8000
  }
  perfumeList.value = []
}

const searchContent = () => {
  perfumeList.value = []
  getPerfumeData(1, 20)
}

const getPerfumeData = (page, item) => {
  let url = `/api/perfume/list/${page}/${item}`
  if (rankFlag.value == '上线时间') {
    url += '?rankUptime=' + (rankDic.value ? 1 : 0)
  } else if (rankFlag.value == '销量') {
    url += '?rankBuy=' + (rankDic.value ? 1 : 0)
  } else if (rankFlag.value == '价格') {
    url += '?rankPrice=' + (rankDic.value == "正序" ? 1 : 0)
  }//排序
  if (sex.value != '') {
    url += '&sex=' + (sex.value == '' ? '' : sex.value == '对他来说' ?
        '男' : sex.value == '对她来说' ? "女" : "中性")
  }//性别
  if (brandId.value != 0) {
    url += "&brandId=" + brandId.value
  }
  if (priceStart.value != 0) {
    url += "&priceStart=" + priceStart.value
  }
  if (priceEnd.value != 0) {
    url += "&priceEnd=" + priceEnd.value
  }
  if (searchText.value != '') {
    url += "&name=" + searchText.value
  }
  searchLoading.value = true
  axios.post(url, {}, {
    headers: {
      token: localStorage.getItem("patient-auth-token")
    }
  })
      .then(res => {
        // console.log(res.data.message)
        const msg = res.data.message
        pageTotal.value = msg.total
        perfumeList.value.push(...msg.list)
        if (perfumeList.value.length == 0) {
          showLoading.value = "暂无香料信息，减少条件试试？"
        } else {
          searchLoading.value = false
        }
      })
}

const getBrandInfoList = () => {
  axios.post("/api/brand/initList",{},{
    headers:{
      token:localStorage.getItem("patient-auth-token")
    }
  }).then(res=>{
    // console.log(res)
    const msg = res.data.message
    brandOptions.value = msg
    brandOptionsText.value = []
    msg.forEach(el=>{
      brandOptionsText.value.push(el.name)
    })
  })
}

const nextPage = () => {
  if ((page.value - 1) * pageItem.value <= pageTotal.value) {
    page.value++
    getPerfumeData(page.value, pageItem.value)
  }

}

onMounted(() => {
  if(route.query.name){
    searchText.value = route.query.name
  }
  getPerfumeData(page.value, pageItem.value)
  getBrandInfoList()
})
// 更新收藏状态的方法
const handleUserCollect = (index: number, newStatus: boolean) => {
  perfumeList.value[index].userCollect = newStatus; // 更新收藏状态
};
const priceBetween =ref({
  min:3000,
  max:8000
})
const diaSearch = () => {
  priceStart.value = priceBetween.value.min
  priceEnd.value = priceBetween.value.max
  console.log(brandText)
  brandOptions.value.forEach(el=>{
    if(el.name == brandText.value){
      brandId.value = el.brandId
    }
  })
  searchContent()
  expandedSearch.value = false
}
const resetSearch = () => {
  reset()
  expandedSearch.value = false
  searchContent()
}
const searchLoading = ref(false)
const showLoading = ref("正在搜索中，请稍等")
</script>

<template>
  <div class="perfumer-main">
    <div class="main-title">香水</div>
    <div class="d-flex align-item-center justify-content-center">
      <q-btn color="blank" flat icon-right="filter_list" label="过滤器" rounded
             @click="expandedSearch = true"/>
      |
      <q-select v-model="rankFlag" :options="rankOptions" label="排序方式" @update:modelValue="searchContent">
        <template v-slot:prepend>
          <q-icon name="sort_by_alpha"/>
        </template>
      </q-select>
      <q-select v-model="rankDic" :options="rankDicOptions" label="排序方向" @update:modelValue="searchContent">
        <template v-slot:prepend>
          <q-icon name="sort_by_alpha"/>
        </template>
      </q-select>
    </div>
    <q-dialog v-model="expandedSearch" persistent>
      <q-card>
        <q-card-section style="display: flex;justify-content: end">
          <q-btn color="red" icon="close" push @click="expandedSearch = false"/>
        </q-card-section>
        <q-card-section style="display: flex">
          <q-select v-model="sex" style="width: 100%;" :options="sexOptions" label="性别">
            <template v-slot:prepend>
              <q-icon name="sex"/>
            </template>
          </q-select>
        </q-card-section>
        <q-card-section style="display: flex">
          <q-select v-model="brandText" style="width: 100%;" :options="brandOptionsText" label="品牌">
            <template v-slot:prepend>
              <q-icon name="sex"/>
            </template>
          </q-select>
        </q-card-section>
        <q-card-section style="display: flex;flex-direction: column">
          <q-badge >
            价格区间: {{ priceBetween.min }} to {{ priceBetween.max }} (0 to 10000)
          </q-badge>

          <q-range
              v-model="priceBetween"
              :min="100"
              :max="99999"
          />
        </q-card-section>

        <q-card-section class="q-pt-none">
          <q-btn-group push>
            <q-btn icon="visibility" label="重置筛选项" @click="resetSearch" push/>
            <q-btn icon="update" label="应用筛选器" push @click="diaSearch"/>
          </q-btn-group>
        </q-card-section>
      </q-card>
    </q-dialog>
    <div class="search-box">
      <q-input v-model="searchText" label="搜索香味..." outlined rounded
               standout="bg-teal text-white" style="width: 60vw" @keyup.enter="searchContent">
        <template v-slot:append>
          <q-icon name="search" @click="searchContent"/>
        </template>
      </q-input>
    </div>
<div class="text-h5" style="margin-left: 6vw;margin-bottom: 20px;">
  fragancias ({{ pageTotal }}
</div>
    <div class="perfume-group">
      <div v-show="searchLoading" class="q-pa-md" style="width: 100%;">
        <div class="q-gutter-md">
          <view style="display: flex;align-items: center">
            <q-skeleton size="100px" type="circle"/>
            <view class="text-h4" style="margin-left: 30px;">{{ showLoading }}</view>
          </view>
          <q-skeleton width="150px"/>
          <q-skeleton height="150px"/>
        </div>
      </div>
      <PerfumeItem v-for="(item,index) in perfumeList" :key="index"
                   :brand-id="item.brandId"
                   :brand-text="item.brandText" :fragrance-note="item.fragranceNote"
                   :img="item.img"
                   :ingredients="item.ingredients"
                   :name="item.name"
                   :perfume-id="item.perfumeId"
                   :price="item.price"
                   :smell="item.smell"
                   :user-collect="item.userCollect"
                   :year="item.year"
                   @updateUserCollect="handleUserCollect(index, $event)"
      />

    </div>
    <div class="add-more-group">
      <q-btn v-if="(page - 1) * pageItem <= pageTotal" color="teal" @click="nextPage">
        <q-icon left name="map" size="3em"/>
        <div>加载更多</div>
      </q-btn>
      <q-btn v-if="(page - 1) * pageItem > pageTotal" align="around" class="btn-fixed-width" color="brown-5"
             icon="lightbulb_outline"
             label="暂无更多数据"/>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.perfumer-main {
  width: 100vw;
  height: 95vh;

  .main-title {
    height: 200px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 40px;
  }

  .search-box {
    width: 100vw;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 200px;
  }

  .perfume-group {
    width: 90%;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: space-between;
    margin-left: 5%;
    margin-right: 5%;
  }

  .add-more-group {
    margin-top: 3vh;
    margin-bottom: 3vh;
    width: 100vw;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
